package com.wmh.baseservice.common.controller;

import com.wmh.baseservice.common.upload.service.CosService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

import static com.wmh.baseservice.common.utils.returnbody.ReturnBody.error;
import static com.wmh.baseservice.common.utils.returnbody.ReturnBody.success;

@RestController
@RequestMapping("/cos")
@Api(tags = "图片上传下载")
@Slf4j
public class CosController {
    @Resource
    private CosService cosService;

    //允许的文件格式
    private final String fileFormat = ".jpg,.jpeg,.png,.gif";

    private final String allowedPackage = ".zip,.rar";

    //文件上传
    @ApiOperation("图片上传")
    @PostMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."), filename.length());
        //判断文件格式是否支持
        if (!fileFormat.contains(suffix.trim().toLowerCase())) {
            return error("文件格式不支持");
        }
        String upload = cosService.upload(file.getBytes(), filename);
        if(!"error".equals(upload)) {
            log.info("图片上传成功!");
            return success(upload);
        } else {
            log.info("图片上传失败!");
            return error("图片上传失败!");
        }

    }

    //文件下载
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadImage(@RequestParam String imageName) throws IOException {
        log.info("imageName: {}" , imageName);
        return cosService.downloadImage(imageName);
    }


    //根据key获取临时url
    @GetMapping("getUrlByKey")
    public String getUrlByKey(@RequestParam("key") String key) {
        return cosService.geturlBykey(key);
    }

}
